package com.lovo.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.lovo.bean.Throne;
import com.lovo.bean.User;
import com.lovo.service.UserService;
import com.lovo.service.serviceImpl.UserServiceImpl;
import com.lovo.util.CodeMsg;
import com.lovo.util.JwtUtil;
import com.lovo.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UserServlet",urlPatterns = "/user.do")
public class UserServlet extends HttpServlet {
    private UserService us = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        String method = request.getParameter("method");
        if(method == null || "".equalsIgnoreCase(method)){
            String page = request.getParameter("page");
            int pageNo = 0;
            if(page == null || "".equalsIgnoreCase(page)){
                pageNo = 1;
            }else{
                pageNo = Integer.parseInt(page);
            }
            String limit = request.getParameter("limit");
            PageInfo<User> pageInfo = us.getUsers(pageNo,Integer.parseInt(limit));
            Result<PageInfo<User>> result = null;
            if(pageInfo == null){
                result = Result.error(CodeMsg.NOTFOUND_ERROR);
            }else{
                result = Result.success(pageInfo);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().write(json);
        }else if(method.equalsIgnoreCase("addUser")){
            String userName = request.getParameter("userName");
            String userTel = request.getParameter("userTel");
            String userEmail = request.getParameter("userEmail");
            String userPwd = request.getParameter("userPwd");
            User user = new User();
            user.setUserEmail(userEmail);
            user.setUserTel(userTel);
            user.setUserName(userName);
            user.setUserPwd(userPwd);
            boolean flag = us.addUser(user);
            Result<String> result = Result.success(String.valueOf(flag));
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().write(json);
        }else if(method.equalsIgnoreCase("updateUser")){
            String userId = request.getParameter("userId");
            String userName = request.getParameter("userName");
            String userTel = request.getParameter("userTel");
            String userEmail = request.getParameter("userEmail");
            String userPwd = request.getParameter("userPwd");

            User user = new User();
            user.setUserPwd(userPwd);
            user.setUserName(userName);
            user.setUserTel(userTel);
            user.setUserEmail(userEmail);
            user.setUserId(Integer.parseInt(userId));

            boolean flag = us.updateUser(user);
            Result<String> result = Result.success(String.valueOf(flag));
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            response.getWriter().write(s);
        }else if(method.equalsIgnoreCase("deleteUser")){
            String userId = request.getParameter("userId");
            boolean flag = us.deleteUser(Integer.parseInt(userId));
            Result<String> result = Result.success(String.valueOf(flag));
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            response.getWriter().write(s);
        }else if(method.equalsIgnoreCase("queryUser")) {
            String content = request.getParameter("content");
            String type = request.getParameter("type");
            String page = request.getParameter("page");
            String limit = request.getParameter("limit");
            PageInfo<User> pageInfo = us.queryUser(type, content, Integer.parseInt(page), Integer.parseInt(limit));
            Result<PageInfo<User>> result = null;
            if (pageInfo == null) {
                result = Result.error(CodeMsg.NOTFOUND_ERROR);
            } else {
                result = Result.success(pageInfo);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().write(json);
        } else if(method.equalsIgnoreCase("login")){
            String userName = request.getParameter("userName");
            String userPwd = request.getParameter("pwd");
            User user = us.login(userName,userPwd);
            Result<User> r = null;
            if(user != null && user.getUserId() > 0) {
                r = Result.success(user);
                String token = JwtUtil.createJWT(6000000, user);
                response.setHeader("Authorization", token);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(r);
            System.out.println("json = " + json);
            response.getWriter().write(json);


        }else if(method.equalsIgnoreCase("verify")){
            String authHeader = request.getHeader("authorization");
            System.out.println(authHeader);

            //截取前面的Bearer
            String token = authHeader.substring(7);
            // 获取 token 中的 user id
            int userId;
            try {
                userId = JWT.decode(token).getClaim("id").asInt();
            } catch (JWTDecodeException j) {
                throw new RuntimeException("访问异常！");
            }

            User user = us.getUserById(userId);

            Result<User> r = null;
            if(user != null){
                Boolean verify = JwtUtil.isVerify(token, user);
                if(verify){
                    r = Result.success(user);
                }
                else{
                    r = Result.error(CodeMsg.PASSWORD_ERROR);
                }

            }
            else{
                r = Result.error(CodeMsg.NOTFOUND_ERROR);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(r);
            response.getWriter().write(json);

        }
    }
}
